package com.pangolin.pangolinim.utils;
import android.util.Base64;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author lq
 * @version V1.0
 * @desc AES 加密工具类
 */
public class AESUtil {
    public static final String CODE = "utf-8";
    private static final String KEY_ALGORITHM = "AES";
    /*** 默认的加密算法 */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(byte[] password) throws Exception {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        /*KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(password);
        //AES 要求密钥长度为 128
        kg.init(128, secureRandom);
        //生成一个密钥
        SecretKey secretKey = kg.generateKey();
        // 转换为AES专用密钥
        return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);*/

        // * 从android 9（API28）开始，以上调用获取不到SecureRandom
        return new SecretKeySpec(InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(password, 32), "AES");
    }

    public static String encrypt(String sSrc , String sKey) throws Exception  {
        byte[] raw = Base64.decode(sKey.getBytes(CODE),  Base64.NO_WRAP);
        SecretKeySpec skeySpec =getSecretKey(raw);
        //Log.d("encrypt Key" , Base64.encodeToString(skeySpec.getEncoded(),  Base64.NO_WRAP));

        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(CODE));
        //Log.d("enMsg1" , Base64.encodeToString(encrypted,  Base64.NO_WRAP));
        return Base64.encodeToString(encrypted,  Base64.NO_WRAP);
    }

    public static String decrypt(String ensSrc , String sKey) throws Exception  {
        byte[] sSrc = Base64.decode(ensSrc,  Base64.NO_WRAP);
        byte[] raw = Base64.decode(sKey.getBytes(CODE),  Base64.NO_WRAP);
        SecretKeySpec skeySpec = getSecretKey(raw);
        //Log.d("enMsg2" , Base64.encodeToString(sSrc,  Base64.NO_WRAP));
        //Log.d("decrypt Key:%s" , Base64.encodeToString(skeySpec.getEncoded(),  Base64.NO_WRAP));
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] crypted = cipher.doFinal(sSrc);
        //Log.d("Msg" , new String(crypted, CODE));
        return new String(crypted, CODE);
    }
}